﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using BusinessLibary;
using IMedicare;
using EntityLibrary;

namespace Medicare
{
    public partial class FrmUpLoadChargeItem : Form
    {

        public FrmUpLoadChargeItem()
        {
            InitializeComponent();
            chargeItemInfoFacade = new ChargeItemInfoFacade();
        }

        private IMedicare.IMedicare medicare;
        private ChargeItemInfoFacade chargeItemInfoFacade;
        private DataView dv = new DataView();

        private string medicareNO = string.Empty;
        private string inhosid = string.Empty;
        private int retint = 0;

        private DataSet chargeItemInfo = new DataSet();
        private ArrayList PrenoList = new ArrayList();
        private readonly string REPORTS_FILE = Application.StartupPath + "\\REPORTS\\医保病人住院结算数据.rmf";

        private string accountBalance = "0";//账户余额

        #region 查询所有处方
        /// <summary>
        /// 查询所有处方
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FrmQueryCF frm = new FrmQueryCF();

            if (frm.ShowDialog() == DialogResult.OK)
            {
                medicareNO = frm.MedicareNo;//实际上是住院号
                inhosid = frm.MedicareNo;//获取住院号
                if (medicareNO.Equals(string.Empty))
                {
                    MessageBox.Show("不完整的医保信息，请重新查询！");
                    return;
                }


            }
            else
            {
                return;
            }
            chargeItemInfo = null;
            try
            {
                chargeItemInfo = chargeItemInfoFacade.BuildChargeInfoByInhosID(medicareNO);

            }
            catch
            {

                MessageBox.Show("连接HIS服务器失败！请检查医院网络或联系管理员！");
            }
            if (chargeItemInfo == null)
            {
                MessageBox.Show("对不起，没有找到该病人的信息！");
                gridControl.DataSource = null;
                //gridView.Columns.Clear();
                return;
            }
            dv = chargeItemInfo.Tables[0].DefaultView;

            gridControl.DataSource = dv;

            foreach (DataRow row in chargeItemInfo.Tables[0].Rows)
            {
                if (row["项目中心编码"].ToString().Equals("AAAAA"))
                {
                    MessageBox.Show("存在未对应的医院收费项目，无法将该病人的收费信息上传到医保中心。请将未对应的项目进行对应后进行上传！");
                    return;
                }
            }
            btnUpLoad.Enabled = true;
            btnPreCalc.Enabled = true;
            btnCalc.Enabled = true;


        }


        #endregion

        #region 上传按钮触发事件

        /// <summary>
        /// 上传按钮触发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpLoad_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (MessageBox.Show("您确定要上传该医保号的处方吗？") == DialogResult.OK)
            {

                if (chargeItemInfo != null)
                {
                    ShowPresonInfo();
                    if (!Validate())
                    {
                        return;
                    }
                    if (chargeItemInfo.Tables[0].Rows.Count <= 0)
                    {
                        MessageBox.Show("没有要上传的处方！");
                    }
                    else
                    {
                        inhosid = chargeItemInfo.Tables[0].Rows[0]["住院号"].ToString();
                        retint = medicare.InHosCharge(1, 1, "", inhosid, 2, null, chargeItemInfo, null, ref PrenoList);
                        if (retint == 0)
                        {
                            MessageBox.Show("上传处方成功");

                        }
                        else
                        {
                            MessageBox.Show("上传处方失败,该病人的处方明细已经上传！");
                        }
                    }

                }

            }
        }

        #endregion

        #region 验证医保号和读卡的医保号是否一致
        /// <summary>
        /// 验证医保号和读卡的医保号是否一致
        /// </summary>
        /// <returns></returns>
        private bool Validate()
        {
            DataSet ds = info.FindbyRegistedPatientInfoByInhosID(inhosid);
            if (ds.Tables[0].Rows.Count > 0)
            {
                if (!medicareNoCard.Equals(ds.Tables[0].Rows[0]["MEDICARENO"].ToString()))
                {
                    MessageBox.Show("获取个人信息返回的医保号与该病人登记的医保号不符，请确认或者重新获取该病人的信息！");
                    return false;
                }
            }
            else
            {
                MessageBox.Show("没有找到该病人的医保登记信息！");
            }
            return true;
        }


        #endregion


        private void FrmUpLoadChargeItem_Load(object sender, EventArgs e)
        {
            medicare = IMedicare.IMedicareFactory.Instance.CreateIMedicare();//s
            ArrayList list = new ArrayList();
            retint = medicare.InitHisDLL(list);
            if (retint != 0)
            {
                MessageBox.Show("医保接口初始化失败，请检查医保网络！");
                return;
            }
        }

        //预结算
        private void btnPreCalc_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowPresonInfo();//显示信息实体
            if (!Validate())
            {
                return;
            }

            string jbmc = string.Empty;
            string jbbm = string.Empty;
            string accountpay = string.Empty;
            string reasonLeaveHos = string.Empty;

            FrmSelectTradeTypeForRZ selectTradeType = new FrmSelectTradeTypeForRZ(accountBalance);
            if (DialogResult.OK == selectTradeType.ShowDialog())
            {
                jbmc = selectTradeType.bzmc;
                jbbm = selectTradeType.bzbm;
                accountpay = selectTradeType.accountPay;
                reasonLeaveHos = selectTradeType.reasonLeaveHos;

            }
            else
            {
                MessageBox.Show("请更新该病人的结算信息，然后进行结算！");
                return;
            }

            PrenoList.Clear();
            PrenoList.Add(jbmc);
            PrenoList.Add(jbbm);
            PrenoList.Add(accountpay);
            PrenoList.Add(reasonLeaveHos);


            retint = medicare.InHosBalance(1, 0, "", inhosid, 2, null, ref PrenoList);
            if (retint != 0)
            {
                MessageBox.Show("预结算失败！");
            }
            else
            {
                string prenolist = PrenoList[0].ToString();
                Display(prenolist);
            }

        }

        public void Display(string prenolist)
        {
            string[] split = prenolist.ToString().Split('|');
            FrmBalanceInfo b = new FrmBalanceInfo();
            b.textBox1.Text = split[15];
            b.textBox2.Text = split[16];
            b.textBox3.Text = split[17];
            b.textBox4.Text = split[18];
            b.textBox5.Text = split[19];
            b.textBox11.Text = split[20];
            b.textBox6.Text = split[25];
            b.textBox7.Text = split[26];
            b.textBox8.Text = split[27];
            b.textBox9.Text = split[28];
            b.textBox10.Text = split[29];
            b.textBox12.Text = split[30];

            b.ShowDialog();


        }
        private string medicareNoCard = string.Empty;

        public void ShowPresonInfo()
        {
            DataSet paientInfo = new DataSet();
            ArrayList PrenoList = new ArrayList();
            retint = medicare.ReadCard(1, "", ref paientInfo, ref PrenoList);
            if (retint != 0)
            {
                return;
            }

            string[] split = PrenoList[0].ToString().Split('^')[2].Split('|');

            string birthdaystr = "1900-01-01";
            try
            {
                //19400827
                //Convert.ToDateTime(split[39].Substring(0, 4) + "-" + split[39].Substring(4, 2) + "-" + split[39].Substring(6, 2));
                birthdaystr = split[14].Substring(0, 4) + "-" + split[14].Substring(4, 2) + "-" + split[14].Substring(6, 2);
                //birthdaystr = split[7];                 //生日返回的格式 1900-01-01
            }
            catch (Exception)
            {
                birthdaystr = "1900-01-01";
            }


            FrmPersonInfo frm = new FrmPersonInfo();
            frm.PersonName.Text = split[3];
            frm.Sex.Text = split[4];
            frm.birthday.Text = split[6];
            frm.age.Text = Convert.ToString(System.DateTime.Today.Year - Convert.ToDateTime(birthdaystr).Year);
            frm.MedID.Text = split[0];
            medicareNoCard = split[0];//读卡获取医保号 与实际登记的匹配
            frm.CardNo.Text = split[9];
            frm.idcardno.Text = split[2];
            frm.unitno.Text = split[16];
            frm.unitname.Text = split[17];


            #region 增加银行卡读卡获取卡余额

            frm.AccountBalance.Text = split[33].ToString();

            PosChantEnity entity = new PosChantEnity();
            entity.MerchanCode = "03";
            entity.MerchanMoney = "";
            entity.POSFlowNo = DateTime.Now.ToString("MMddss");
            entity.CashMemberNo = "";
            entity.CashRegNo = "";
            entity.OrginTerminalNo = "";
            entity.AuthorizationNo = "";
            entity.OrginTranDT = "";
            entity.TerminalType = "7";
            entity.Track1 = "";
            entity.Track2 = "5226085710076865=49121200352600812761";
            entity.Track3 = "996226095710076865=1561560500050000001015812761214000049120=5710076865=000000000=00000000571000000000000";
            accountBalance = medicare.ShowBalance(entity);

            #endregion

            //accountBalance = split[33].ToString(); //账户余额赋值
            frm.persontype.Text = split[10];
            frm.InHosTimes.Text = split[47].ToString();
            frm.InHosState.Text = split[34] == "1" ? "住院" : "出院";
            frm.textBox16.Text = split[37];//年度帐户支付累计
            frm.textBox15.Text = split[38];//统筹基金支付
            frm.ShowDialog();
        }

        //正式结算
        private void btnCalc_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowPresonInfo();//显示信息实体
            if (!Validate())
            {
                return;
            }

            string jbmc = string.Empty;
            string jbbm = string.Empty;
            string accountpay = string.Empty;
            string reasonLeaveHos = string.Empty;

            FrmSelectTradeTypeForRZ selectTradeType = new FrmSelectTradeTypeForRZ(accountBalance);
            if (DialogResult.OK == selectTradeType.ShowDialog())
            {

                jbmc = selectTradeType.bzmc;
                jbbm = selectTradeType.bzbm;
                accountpay = selectTradeType.accountPay;
                reasonLeaveHos = selectTradeType.reasonLeaveHos;

            }
            else
            {
                MessageBox.Show("请更新该病人的结算信息，然后进行结算！");
                return;
            }


            PrenoList.Clear();
            PrenoList.Add(jbmc);
            PrenoList.Add(jbbm);
            PrenoList.Add(accountpay);
            PrenoList.Add(reasonLeaveHos);

            string prenolist = string.Empty;//医保返回的结算字符串

            retint = medicare.InHosBalance(3, 0, "", inhosid, 2, null, ref PrenoList);
            if (retint != 0)
            {
                MessageBox.Show("正式结算结算失败！");
                return;
            }
            else
            {
                prenolist = PrenoList[0].ToString();
                Display(prenolist);
            }

            if (MessageBox.Show("结算成功，是否需要打印？", "打印", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                DataSet ds = info.FindbyRegistedPatientInfoByInhosID(inhosid);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    PrintReport(ds,prenolist);
                }
                else
                {
                    MessageBox.Show("打印失败！");
                }


            }

        }

        private RegisterInfoFacade info = new RegisterInfoFacade();

        private void btnQuit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            PrenoList.Clear();
            medicare.FreeHisDLL(PrenoList);
            this.Close();
        }


        #region 打印报表
        //打印报表
        private void PrintReport(DataSet ds,string prenolist)
        {
            RMReportEngine.RMReport rmReport = new RMReportEngine.RMReport();
            rmReport.Init(this, RMReportEngine.RMReportType.rmrtReport);
            //rmReport.AddDataSet(ds.Tables[0], "report");

            string inhosID = ds.Tables[0].Rows[0]["INHOSID"].ToString();
            string idCardNo = ds.Tables[0].Rows[0]["IDCARDNO"].ToString();
            string paientname = ds.Tables[0].Rows[0]["hzxm"].ToString();

            string TotalFee = ds.Tables[0].Rows[0]["PRE0"].ToString();
            string tczc = ds.Tables[0].Rows[0]["PRE1"].ToString();
            string dbzc = ds.Tables[0].Rows[0]["PRE2"].ToString();
            string zhzc = ds.Tables[0].Rows[0]["PRE3"].ToString();
            string xjzc = ds.Tables[0].Rows[0]["PRE4"].ToString();
            string gwybzzc = ds.Tables[0].Rows[0]["PRE5"].ToString();
            string zfje = ds.Tables[0].Rows[0]["PRE6"].ToString();
            string txfdzf = ds.Tables[0].Rows[0]["PRE7"].ToString();
            string dbfdzf = ds.Tables[0].Rows[0]["PRE8"].ToString();
            string yydf = ds.Tables[0].Rows[0]["PRE9"].ToString();
            string trandt = ds.Tables[0].Rows[0]["TRANDT"].ToString();

            string medicareNo = ds.Tables[0].Rows[0]["MEDICARENO"].ToString();



            string[] split = prenolist.ToString().Split('|');






            rmReport.AddVariable("患者姓名", paientname, true);
            rmReport.AddVariable("住院号", inhosID, true);
            rmReport.AddVariable("身份证号", idCardNo, true);
            rmReport.AddVariable("本次医疗费用", TotalFee, true);
            rmReport.AddVariable("本次统筹支出", tczc, true);
            rmReport.AddVariable("本次大病支出", dbzc, true);
            rmReport.AddVariable("本次账户支出", zhzc, true);
            rmReport.AddVariable("本次现金支出", xjzc, true);
            rmReport.AddVariable("本次公务员补助支出", gwybzzc, true);
            rmReport.AddVariable("本次自费金额", zfje, true);
            rmReport.AddVariable("统筹分段支付", txfdzf, true);
            rmReport.AddVariable("大病分段支付", dbfdzf, true);
            rmReport.AddVariable("医院垫付", yydf, true);
            rmReport.AddVariable("交易日期", trandt, true);
            rmReport.AddVariable("操作员", ToolUltity.LoginUser.USERNAME, true);


            rmReport.AddVariable("药品", split[56], true);
            rmReport.AddVariable("检查检验", split[59], true);
            rmReport.AddVariable("治疗", split[62], true);
            rmReport.AddVariable("手术麻醉", split[65], true);
            rmReport.AddVariable("材料", split[68], true);
            rmReport.AddVariable("服务设施", split[71], true);
            rmReport.AddVariable("其他", split[74], true);
            rmReport.AddVariable("起付线", split[27], true);
            rmReport.AddVariable("医保号", medicareNo, true);
           



            rmReport.LoadFromFile(REPORTS_FILE);

            ////打印 or 预览
            //if (rdbPreview.Checked)
            //{
            //    rmReport.ShowReport();
            //}
            //else
            //{

            //}

            rmReport.PrintReport();
            rmReport.Dispose();
            rmReport.Destroy();
        }


        #endregion

        /// <summary>
        /// 指定自费checkbox状态改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemCheckEdit1_CheckStateChanged(object sender, EventArgs e)
        {
            int rowhandle = gridView.FocusedRowHandle;
            DataRow row = gridView.GetDataRow(rowhandle);
            int t = 2;
            if (Convert.ToBoolean(row["STATE"]) == true)
                t = 0;
            //gridView1.SetRowCellValue(rowhandle, "SELFMONEY",t);
            row.BeginEdit();
            row["SELFMONEY"] = t;
            row.EndEdit();

            //  MessageBox.Show("自费为" + row["SELFMONEY"].ToString());
            gridView.CloseEditor();
        }

        private void btnPosTrant_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {


            FrmPosTran tran = new FrmPosTran();
            if (DialogResult.OK == tran.ShowDialog())
            {
                PosChantEnity entity = new PosChantEnity();
                entity.MerchanCode = "01";
                entity.MerchanMoney = (Double.Parse(tran.TranMoney) * 100).ToString();
                entity.POSFlowNo = DateTime.Now.ToString("MMddss");
                entity.CashMemberNo = "";
                entity.CashRegNo = "";
                entity.OrginTerminalNo = "";
                entity.AuthorizationNo = "";
                entity.OrginTranDT = "";
                entity.TerminalType = "7";
                entity.Track1 = "";
                entity.Track2 = "5226085710076865=49121200352600812761";
                entity.Track3 = "996226095710076865=1561560500050000001015812761214000049120=5710076865=000000000=00000000571000000000000";

                if (IMedicare.IMedicareFactory.Instance.CreateInterface<SDRZDRInterface>().CandTrans(entity).Success)
                    MessageBox.Show("划卡成功!");
                else
                    MessageBox.Show("划卡失败!");

            }

        }


    }
}
